/*
 * @Description: 启动页面   SplashPage
 * @version: 
 * @Company: 
 * @Author: ZhengZhuang
 * @Date: 2019-08-31 14:19:23
 * @LastAuthor: zhengzhuang
 * @lastTime: 2020-02-29 13:53:55
 */
import 'dart:async';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:C20Driver/resources/app_storage_interface.dart';
import 'package:C20Driver/service/request.dart';
import 'package:C20Driver/utils/toast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> with WidgetsBindingObserver {
  int _status = 0; // 0：纯启动页  1：第一次打开App欢迎轮播图  2：广告图3s倒计时
  bool _getIntoState = true;
  bool _countDownState = false;
  Timer _countdownTimer;
  int _countdownNum = 3;
  // Uint8List _splashImg; // 启动图片
  String _splashImg; // 启动图片

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    _firstOpenState();
  }

  /// 获取动态广告图
  void _getAdvertPicture() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _splashImg = prefs.getString(AppStorageInterface.ADVERTPICTUREIMG);

    await Request.advertPicture();
  }

  // 判断是否是首次打开
  _firstOpenState() async {
    SharedPreferences pres = await SharedPreferences.getInstance();
    String firstOpenStateData = pres.get(AppStorageInterface.FIISTOPENSTATE);
    if (firstOpenStateData == null) {
      // 修改本地存储状态变为非首次打开
      _openAlertDialog(context);

    } else {
       _appLoginStatus();
    }
  }



  // 判断当前显示是那种类型的欢迎页
  _judgingWelcomeTypes() async {
    if (_status == 0) return _appLoginStatus();
  }

  Future<String> getLoginState() async {
    String getToken = '';
    SharedPreferences prefs = await SharedPreferences.getInstance();
    getToken = prefs.getString(AppStorageInterface.LOGINTOKEN); // 存储token到本地

    print('token ======= $getToken');
    return getToken;
  }

  // 查看App登录状态,纯启动页动画倒计时
  _appLoginStatus() async {
    Future<String> appToken = getLoginState();
    return appToken.then((String appToken) async {
      Timer(Duration(seconds: 1), () {
        if (appToken == '' || appToken == null) {
          // 只在倒计时结束时回调

print("appToken =========null");
NavigatorUtil.goToHomeRemovePage(context);
        } else {
          // 只在倒计时结束时回调
          // print("纯启动页动画倒计时");
          NavigatorUtil.goToHomeRemovePage(context);
        }
      });
    });
  }

  void reGetCountdown() {
    setState(() {
      if (_countdownTimer != null) return;
      // Timer的第一秒倒计时是有一点延迟的，为了立刻显示效果可以添加下一行。
      _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
        setState(() {
          if (_countdownNum > 0) {
            _countdownNum--;
          } else {
            NavigatorUtil.goToHomeRemovePage(context);
            _countdownTimer.cancel();
            _countdownTimer = null;
          }
        });
      });
    });
  }

  @override
  void dispose() {
    if (_countdownTimer != null) {
      _countdownTimer.cancel();
    }
    _countdownTimer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);
    // SystemChrome.setEnabledSystemUIOverlays([]);
    // 白色
    // SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    return Scaffold(
      body: Container(
        child: Stack(
          children: <Widget>[
            // 纯欢迎页图片
            Offstage(
              offstage: !(_status == 0),
              child: _welcomePictures(),
            ),
            // app欢迎引导页
            Offstage(
              offstage: !(_status == 1),
              child: _guidePage(),
            ),
          ],
        ),
      ),
    );
  }

  // 欢迎页图片
  Widget _welcomePictures() {
    final EdgeInsets padding = MediaQuery.of(context).padding;
    return Stack(
      children: <Widget>[
        Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height + MediaQuery.of(context).padding.top,
          child: _splashImg == null
              ? Image.asset(
            'assets/icon/launch_background.png',
            width: double.infinity,
            height: double.infinity,
            // scale: 2.0, //进行缩放
            fit: BoxFit.cover,
          )
              : CachedNetworkImage(
            width: double.infinity,
            height: double.infinity,
            imageUrl: _splashImg,
            fit: BoxFit.cover,
            placeholder: (context, url) =>Container(),
            errorWidget: (context, url, error) => Icon(Icons.error),
          ),
        ),
        Positioned(
          top: padding.top,
          right: ScreenUtil().setWidth(10.0),
          child: Offstage(
            offstage: !_countDownState,
            child: InkWell(
              child: Container(
                width: ScreenUtil().setSp(151.0),
                height: ScreenUtil().setSp(66.0),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color.fromARGB(100, 0, 0, 0),
                    borderRadius: BorderRadius.all(Radius.circular(20.0))),
                child: Text(
                  '跳过$_countdownNum',
                  // '$_countdownNum',
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(32.0), color: Colors.white),
                ),
              ),
              onTap: () => NavigatorUtil.goToHomeRemovePage(context),
            ),
          ),
        ),
      ],
    );
  }

  // 第一次打开app欢迎引导页
  Widget _guidePage() {
    List dataList = [
      'assets/icon/appWelcome/boot_page1.png',
      'assets/icon/appWelcome/boot_page2.png',
      'assets/icon/appWelcome/boot_page3.png',
    ];
    return Stack(
      children: <Widget>[
        Container(
          width: ScreenUtil().setWidth(750.0),
          child: Swiper(
            itemBuilder: (BuildContext context, int index) {
              return Image.asset(
                dataList[index],
                fit: BoxFit.fill,
              );
            },
            loop: false,
            autoplay: false,
            itemCount: dataList.length,
            pagination: SwiperPagination(),
            onIndexChanged: (index) {
              if (index == 2) {
                setState(() {
                  _getIntoState = false;
                });
              } else {
                setState(() {
                  _getIntoState = true;
                });
              }
            },
          ),
        ),
        Positioned(
          bottom: ScreenUtil().setWidth(80.0),
          right: ScreenUtil().setWidth(225.0),
          child: Offstage(
            offstage: _getIntoState,
            child: MaterialButton(
              minWidth: ScreenUtil().setWidth(300.0),
              height: ScreenUtil().setWidth(80.0),
              color: Colors.blue,
              child: Text(
                '立即进入',
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
              onPressed: () => NavigatorUtil.goToLoginRemovePage(),
            ),
          ),
        )
      ],
    );
  }

  /// 隐私协议组建
  /// 退出登录当前账号
  Future _openAlertDialog(context) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return WillPopScope(
            child: Material(
              type: MaterialType.transparency,
              child: Container(
                margin: EdgeInsets.all(ScreenUtil().setWidth(48.0)),
                decoration: BoxDecoration(
                  borderRadius:
                  BorderRadius.circular(ScreenUtil().setWidth(20.0)),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Container(
                      alignment: Alignment.center,
                      color: Colors.white,
                      child: Column(
                        children: <Widget>[
                          SizedBox(height: ScreenUtil().setWidth(20.0)),
                          Padding(
                            padding: EdgeInsets.only(top: 8),
                            child: Text('温馨提示',
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(30.0),
                                    color: Color.fromARGB(255, 51, 51, 51),
                                    fontWeight: FontWeight.w500,
                                    decoration: TextDecoration.none)),
                          ),
                          SizedBox(height: ScreenUtil().setWidth(30.0)),
                          Container(
                            width: ScreenUtil().setWidth(600.0),
                            child: Column(
                              children: [
                                Text(
                                  '亲爱的用户，感谢您对C20出行一直以来的信任！',
                                  textAlign: TextAlign.justify,
                                  style: TextStyle(
                                    fontSize: ScreenUtil().setSp(28.0),
                                    color: Color.fromARGB(255, 102, 102, 102),
                                  ),
                                ),
                                RichText(
                                  text: TextSpan(
                                      text: "我们依据最新的监管要求更新了C20出行的",
                                      style: TextStyle(
                                        fontSize: ScreenUtil().setSp(28.0),
                                        color:
                                        Color.fromARGB(255, 102, 102, 102),
                                      ),
                                      children: <TextSpan>[
                                        TextSpan(
                                          text: "《隐私政策》",
                                          style: TextStyle(
                                            fontSize: ScreenUtil().setSp(28.0),
                                            color: Color(0xff3FB956),
                                          ),
                                          recognizer: TapGestureRecognizer()
                                            ..onTap = () =>
                                                NavigatorUtil.jumpWebView(
                                                    context,
                                                    'http://c20h5.huashichuxing.com/yinsizhengce'),
                                        ),
                                        TextSpan(
                                          text: "和",
                                          style: TextStyle(
                                            fontSize: ScreenUtil().setSp(28.0),
                                            color: Color.fromARGB(
                                                255, 102, 102, 102),
                                          ),
                                        ),
                                        TextSpan(
                                          text: "《用户协议》",
                                          style: TextStyle(
                                            fontSize: ScreenUtil().setSp(28.0),
                                            color: Color(0xff3FB956),
                                          ),
                                          recognizer: TapGestureRecognizer()
                                            ..onTap = () =>
                                                NavigatorUtil.jumpWebView(
                                                    context,
                                                    'http://c20h5.huashichuxing.com/serviceAgreement'),
                                        ),
                                        TextSpan(
                                          text: "特向您说明，详情请点击阅读。",
                                          style: TextStyle(
                                            fontSize: ScreenUtil().setSp(28.0),
                                            color: Color.fromARGB(
                                                255, 102, 102, 102),
                                          ),
                                        ),
                                      ]),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(height: ScreenUtil().setWidth(30.0)),
                          Container(
                            // padding: EdgeInsets.only(top: 15, bottom: 8),
                              decoration: BoxDecoration(
                                  border: Border(
                                      top: BorderSide(
                                          width: ScreenUtil().setWidth(1.0),
                                          color: Colors.black12))),
                              child: Row(
                                children: [
                                  FlatButton(
                                      minWidth: ScreenUtil().setWidth(326.0),
                                      height: ScreenUtil().setWidth(100.0),
                                      onPressed: () async {
                                        ToastX.center("请同意条款后使用c20出行服务");
                                        // 关闭 Dialog
                                      },
                                      child: Text('不同意',
                                          style: TextStyle(
                                              color: Color.fromARGB(
                                                  255, 153, 153, 153),
                                              fontSize:
                                              ScreenUtil().setSp(30.0)))),
                                  SizedBox(
                                    width: ScreenUtil().setWidth(2.0),
                                    height: ScreenUtil().setWidth(100.0),
                                    child: DecoratedBox(
                                      decoration:
                                      BoxDecoration(color: Colors.black12),
                                    ),
                                  ),
                                  FlatButton(
                                      minWidth: ScreenUtil().setWidth(326.0),
                                      height: ScreenUtil().setWidth(100.0),
                                      onPressed: () async {
                                        var sp = await SharedPreferences
                                            .getInstance();
                                        sp.setString("isAgree", "agree");
                                        sp.setString(AppStorageInterface.FIISTOPENSTATE, 'false');
                                        Navigator.pop(context, 'cancel');
                                        NavigatorUtil.goToLoginRemovePage();
                                      },
                                      child: Text('同意',
                                          style: TextStyle(
                                              color: Color(0xff3FB956),
                                              fontSize:
                                              ScreenUtil().setSp(30.0)))),
                                ],
                              ))
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
            onWillPop: () async => false);
      },
    );
  }
}
